package com.atguigu.edu.publisher.controller;

import com.atguigu.edu.publisher.beans.TrafficVisitorTypeStatsBean;
import com.atguigu.edu.publisher.service.TrafficVisitorStatsService;
import com.atguigu.edu.publisher.utils.DateFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class TrafficVisitorStatsController {
    @Autowired
    TrafficVisitorStatsService trafficVisitorStatsService;

    @RequestMapping("/visitorStats")
    public String getVisitorPerType(@RequestParam(value = "date", defaultValue = "0") Integer date){
        if (date == 0){
            date = DateFormatUtil.now();
        }
        StringBuilder res = new StringBuilder("{\"status\": 0,\"data\": {\"total\": 2,\"columns\": [{\"name\": \"新老用户\",\"id\": \"is_new\"},{\"name\": \"独立访客数\",\"id\": \"uv\"},{\"name\": \"页面浏览数\",\"id\": \"pv\"},{\"name\": \"用户跳出率\",\"id\": \"uj_rate\",\"accuracy\": 2},{\"name\": \"平均在线时长\",\"id\": \"avg_dur\",\"accuracy\": 2},{\"name\": \"平均浏览页面数\",\"id\": \"avg_pv\",\"accuracy\": 2}],\"rows\": [");
        List<TrafficVisitorTypeStatsBean> visitorTypeStats = trafficVisitorStatsService.getVisitorTypeStats(date);
        for (int i = 0; i < visitorTypeStats.size(); i++) {
            TrafficVisitorTypeStatsBean visitorTypeStat = visitorTypeStats.get(i);
            String userType = null;
            if ("1".equals(visitorTypeStat.getIsNew())){
                userType = "new";
            }else{
                userType = "old";
            }
            res.append("{\"is_new\": \""+ userType
                    +"\",\"uv\": \""+ visitorTypeStat.getUvCt()
                    +"\",\"pv\": \""+ visitorTypeStat.getPvCt()
                    +"\",\"uj_rate\": \""+ visitorTypeStat.getUjRate()
                    +"\",\"avg_dur\": "+ visitorTypeStat.getAvgDurSum()
                    +",\"avg_pv\": \"" + visitorTypeStat.getAvgPvCt() + "\"}");
            if (i<visitorTypeStats.size()-1){
                res.append(",");
            }
        }
        res.append("]}}");
        return res.toString();
    }
}
